package view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.laoxinwen.app.R;

/**
 * Created by ilioili on 2015/3/16.
 */
public class FixedFrame extends FrameLayout {
    private boolean baseOnWidth;
    private int h = 1;
    private int w = 1;

    public FixedFrame(Context context) {
        this(context, null);
    }


    public FixedFrame(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.FixedImageView);
        w = array.getInt(R.styleable.FixedImageView_w, 1); //提供默认值，放置未指定
        h = array.getInt(R.styleable.FixedImageView_h, 1);
        baseOnWidth = array.getBoolean(R.styleable.FixedImageView_h, true);
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (baseOnWidth) {
            height = width * h / w;
        } else {
            width = height * w / h;
        }
        setMeasuredDimension(width, height);
        measureChildren(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (0 != getChildCount()) {
            getChildAt(0).layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
        }
    }
}
